package com.gitee.sop.layui.adminserver.module.base.view;

import com.gitee.sop.layui.adminserver.plugins.shiro.LoginExceptionManager;
import com.gitee.sop.layui.adminserver.plugins.shiro.LoginTypeToken;
import com.gitee.sop.layui.adminserver.plugins.shiro.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author: huwei
 * @date: 2019/9/12 17:03
 * @version: 1.3.0
 */
@Slf4j
@Controller
public abstract class BaseLoginViewController extends BaseViewController {

    @PostMapping(value = {"/login"})
    public ModelAndView login(ModelAndView modelAndView, String username, String password, HttpServletRequest request, HttpServletResponse response) {
        LoginTypeToken usernamePasswordToken = getCustomShiroToken(request, username, password);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);

            //登录成功初始化
            loginedInit();

            //重定向到主页
            modelAndView.setViewName("redirect:".concat(loginedAfterToUri(request, response)));
        } catch (Throwable e) {
            log.error("登录异常", e);
            toLogin(modelAndView, LoginExceptionManager.errorMsg(e), request, response);
        }
        return modelAndView;
    }

    @RequestMapping(value = {"/toLogin"})
    public ModelAndView toLogin(ModelAndView modelAndView, String msg, HttpServletRequest request, HttpServletResponse response) {
        modelAndView.setViewName(prefix().concat("/login.html"));
        modelAndView.addObject("msg", msg);
        return modelAndView;
    }

    @RequestMapping(value = {"/logout"})
    public ModelAndView logout(ModelAndView modelAndView) {
        modelAndView.setViewName("redirect:toLogin");
        modelAndView.addObject("msg", "已退出");
        ShiroUtil.getSubject().logout();
        return modelAndView;
    }

    /**
     * 获取一个token对象
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    protected abstract LoginTypeToken getCustomShiroToken(HttpServletRequest request, String username, String password);

    /**
     * 登录成功后重定向uri地址，默认跳转到主页：index.html
     *
     * @return
     */
    protected String loginedAfterToUri(HttpServletRequest request, HttpServletResponse response) {
        return "index.html";
    }

    /**
     * 登录功能初始化
     */
    protected void loginedInit() {
        //session 默认存储7天
        ShiroUtil.getSubject().getSession().setTimeout(TimeUnit.DAYS.toMillis(7));
    }

}
